package com.ebt.m.proposal_v2.ui.view;

import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import com.ebt.m.R;
import com.ebt.m.customer.constant.Dictionary;
import com.ebt.m.customer.ui.DialogCustomerChoose;
import com.ebt.m.customer.view.ConfirmDialog;
import com.ebt.m.data.entity.Customer;
import com.ebt.m.proposal_v2.bean.InsuredEntity;
import com.ebt.m.proposal_v2.dao.response.BusinessConfig;
import com.ebt.m.proposal_v2.event.InsuredChangedEvent;
import com.ebt.m.proposal_v2.helper.PickerHelper;
import com.ebt.m.proposal_v2.interfaces.OnRxClickListener;
import com.ebt.m.proposal_v2.utils.DataUtils;
import com.ebt.m.proposal_v2.utils.InsuredCheckUtils;
import com.ebt.m.proposal_v2.widget.base.CompatLinearLayout;
import com.ebt.m.proposal_v2.widget.dialog.EBTBottomListDialog;
import com.ebt.m.proposal_v2.widget.view.InsuranceCellView;
import com.ebt.m.proposal_v2.widget.view.ProposalHeader;
import com.ebt.m.proposal_v2.widget.view.ProposalPerson;
import com.ebt.m.proposal_v2.widget.view.ProposalPropertyItem;
import com.ebt.m.utils.android.DateUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;

/**
 * 被保人UI
 *
 * @author archer.qi
 *         Created on 2017/5/9.
 */
public class InsuredView extends CompatLinearLayout {

    @BindView(R.id.insured_header)
    ProposalHeader proposalHeader;
    @BindView(R.id.insured_person)
    ProposalPerson proposalPerson;
    @BindView(R.id.insured_relationWithInsured)
    ProposalPropertyItem propertyRelationWith;
    @BindView(R.id.insured_careerLevel)
    ProposalPropertyItem propertyCareer;

    private InsuranceView correspondingInsuranceView;
    private ApplicantView correspondingApplicantView;

    private FragmentManager fragmentManager;
    private DialogCustomerChoose importCustomerDialog;
    /* 当前选中的职业类别*/
    private int currentCareerCode = 1;
    /* 当前选中的与被保人关系*/
    private int currentRelationCode = -1;

    private onInsuredChangedListener onInsuredChangedListener;

    public InsuredView(Context context) {
        super(context);
    }

    public InsuredView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected int setContentView() {
        return R.layout.proposal_v2_insured;
    }

    @Override
    protected void onBindView() {
        proposalPerson.setInsured(true);
        initHeader();
        initPropertyListeners();
        updateRelation();
        updateProposalHeaderView();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        proposalPerson.setCorrespondInsuredView(this);
    }

    private void initHeader() {
        proposalHeader.showRight();
        proposalHeader.addImportCustomerListener(new OnRxClickListener() {
            @Override
            public void onRxClick(View view) {
                importCustomer();
            }
        });
        proposalPerson.setInfoChangedListener(new ProposalPerson.onInfoChangedListener() {
            @Override
            public void onInfoChanged() {
                callChanged(0);
            }
        });
    }

    private boolean forMoreInsuredView;

    public void setForMoreInsuredView(boolean forMoreInsuredView) {
        this.forMoreInsuredView = forMoreInsuredView;
        updateProposalHeaderView();
    }

    private String forMoreInsuredViewTitle = "被保人信息";

    public void setForMoreInsuredViewTitle(String title) {
        forMoreInsuredViewTitle = title;
        updateProposalHeaderView();
    }

    private void updateProposalHeaderView() {
        if (proposalHeader == null) {
            return;
        }
        if (forMoreInsuredView) {
            proposalHeader.setTitle(forMoreInsuredViewTitle);
        } else {
            proposalHeader.setTitle(R.string.proposalKeyInsured);
        }
        if (forMoreInsuredView) {
            proposalHeader.showDelete(true);
        } else {
            proposalHeader.showDelete(false);
        }
    }

    private void initPropertyListeners() {
        propertyCareer.addPropertyChooseListener(new OnRxClickListener() {
            @Override
            public void onRxClick(View view) {
                PickerHelper.pickCareer(fragmentManager, propertyCareer.getValue(), careerListener, propertyCareer.getExceptedDataIndex());
            }
        });

        propertyRelationWith.addPropertyChooseListener(new OnRxClickListener() {
            @Override
            public void onRxClick(View view) {
                PickerHelper.pickRelation(fragmentManager, propertyRelationWith.getValue(), relationListener, propertyRelationWith.getExceptedDataIndex());
            }
        });
    }

    /* 导入客户*/
    private void importCustomer() {
        if (importCustomerDialog == null) {
            importCustomerDialog = DialogCustomerChoose.newInstance(getString(R.string.pro_choose_customer),
                    new DialogCustomerChoose.CustomerChooseListener() {
                        @Override
                        public void onPick(Customer customer) {
                            checkNewCustomer(customer);
                        }
                        @Override
                        public void onCancel() {
                        }
                    });
        }
        importCustomerDialog.show(fragmentManager, "DialogCustomerChoose");
    }

    private void checkNewCustomer(Customer customer){
        final InsuredEntity insuredEntityTemp = new InsuredEntity();
        insuredEntityTemp.name = customer.getName();
        insuredEntityTemp.sex = customer.getSex();
        insuredEntityTemp.age = customer.getAge();
        if (customer.getIsConfirm() != 0) {
            insuredEntityTemp.birthday = DateUtils.dateTime2String(customer.getBirthday());
        }
        insuredEntityTemp.profession = 1;

        ArrayList<Object> ret = InsuredCheckUtils.checkChangeAccordWithInsuranceLimit(true,this, insuredEntityTemp, InsuranceCellView.CHECK_TYPE_AGE);
        if (!(Boolean) ret.get(0)) {
            showConfirmChangeDialog("导入的客户不符合被保条件，是否继续更改？", "更改", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    InsuranceView insuranceView = getCorrespondingInsuranceView();
                    ArrayList<InsuranceCellView> list = insuranceView.getInsuranceCellViews();
                    for (InsuranceCellView cellView : list) {
                        InsuredEntity insuredEntity = InsuredCheckUtils.getApplicantAsInsuredEntity(true, insuredEntityTemp, insuranceView, cellView);
                        cellView.setInsuredEntity(insuredEntity);
                    }

                    if(customer != null) {
                        Date birthday = customer.getBirthday();
                        if (customer.getIsConfirm() == 0) {
                            customer.setAge(DateUtils.getAge(birthday));
                            customer.setBirthday(null);
                        }
                    }
                    proposalPerson.setCustomer(customer);
                    EventBus.getDefault().post(new InsuredChangedEvent(InsuredView.this, correspondingInsuranceView, 0));
                }
            });
        } else {
            InsuranceView insuranceView = getCorrespondingInsuranceView();
            ArrayList<InsuranceCellView> list = insuranceView.getInsuranceCellViews();
            for (InsuranceCellView cellView : list) {
                InsuredEntity insuredEntity = InsuredCheckUtils.getApplicantAsInsuredEntity(true, insuredEntityTemp, insuranceView, cellView);
                cellView.setInsuredEntity(insuredEntity);
            }
            if(customer != null) {
                Date birthday = customer.getBirthday();
                if (customer.getIsConfirm() == 0) {
                    customer.setAge(DateUtils.getAge(birthday));
                    customer.setBirthday(null);
                }
            }
            proposalPerson.setCustomer(customer);
            EventBus.getDefault().post(new InsuredChangedEvent(InsuredView.this, correspondingInsuranceView, 0));
        }
    }

    private EBTBottomListDialog.OnSingleCheckListener careerListener = new EBTBottomListDialog.OnSingleCheckListener() {
        @Override
        public void onSingleCheck(int position, String value) {
            String careerName = value;
            int careerCode = Dictionary.DictionaryUtils.getCareerCodeByName(careerName);

            if (currentCareerCode != careerCode) {
                //todo 检查是否合法
                InsuredEntity insuredEntityTemp = getInsured();
                insuredEntityTemp.profession = careerCode;//新的职业
                InsuranceView parentInsuranceView = getCorrespondingInsuranceView();
                boolean retCheckBoolean = true;
                StringBuilder retCheckString = new StringBuilder();
                if (parentInsuranceView != null) {
                    ArrayList<InsuranceCellView> cellViews = parentInsuranceView.getInsuranceCellViews();
                    for (InsuranceCellView cellView : cellViews) {
                        ArrayList<Object> retCellCheck = cellView.checkIfMatchCondition(insuredEntityTemp);
                        if (!(Boolean) retCellCheck.get(0)) {
                            if (InsuranceCellView.CHECK_TYPE_CAREER == (Integer) retCellCheck.get(2)) {
                                retCheckBoolean = false;
                                retCheckString.append(cellView.getData().getDisplayName());
                                retCheckString.append(" ");
                                retCheckString.append(retCellCheck.get(1));
                            }
                        }
                    }
                }
                if (!retCheckBoolean) {
                    showConfirmChangeDialog("确定要更改职业类别吗？" + retCheckString.toString(), "更改", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            InsuranceView insuranceView = getCorrespondingInsuranceView();
                            ArrayList<InsuranceCellView> list = insuranceView.getInsuranceCellViews();
                            for (InsuranceCellView cellView : list) {
                                cellView.setInsuredEntity(insuredEntityTemp);
                            }

                            currentCareerCode = careerCode;
                            propertyCareer.setValue(careerName);
                            callChanged(0);
                        }
                    });
                } else {
                    InsuranceView insuranceView = getCorrespondingInsuranceView();
                    ArrayList<InsuranceCellView> list = insuranceView.getInsuranceCellViews();
                    for (InsuranceCellView cellView : list) {
                        cellView.setInsuredEntity(insuredEntityTemp);
                    }

                    currentCareerCode = careerCode;
                    propertyCareer.setValue(careerName);
                    callChanged(0);
                }
            }
        }
    };

    private ConfirmDialog confirmDialog;

    private void showConfirmChangeDialog(String message, String positiveButtonText, View.OnClickListener listener) {
        if (confirmDialog == null) {
            confirmDialog = new ConfirmDialog(getContext());
        }
        if (confirmDialog.isShowing()) {
            confirmDialog.dismiss();
        }
        confirmDialog.setMessage(message);
        confirmDialog.setPositiveButton(positiveButtonText, new OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onClick(view);
                confirmDialog.dismiss();
            }
        });
        confirmDialog.show();
    }

    private EBTBottomListDialog.OnSingleCheckListener relationListener = new EBTBottomListDialog.OnSingleCheckListener() {
        @Override
        public void onSingleCheck(int position, String value) {
            String relationName = value;
            int relationCode = Dictionary.DictionaryUtils.getRelationCodeByName(relationName);

            if (currentRelationCode != relationCode) {
                if (otherRelationCallBack != null) {
                    if ((relationCode == 0 || relationCode == 1) && !otherRelationCallBack.checkOtherRelation(relationCode)) {
                        return;
                    }
                }
                currentRelationCode = relationCode;
                propertyRelationWith.setValue(relationName);
                //关系为本人，当关系发生改变时，即变更到本人时，需要更新对应的insuranceView下的cellView的entity保存的insured信息，从而准确判断是否有不符合条件的情况
                if (relationCode == 0) {
                    if (getCorrespondingApplicantView() != null) {
                        bindData(getCorrespondingApplicantView().getCustomer());
                        InsuredEntity currInsuredEntity = getInsured();
                        InsuranceView insuranceView = getCorrespondingInsuranceView();
                        if (insuranceView != null) {
                            ArrayList<InsuranceCellView> list = insuranceView.getInsuranceCellViews();
                            for (InsuranceCellView cellView : list) {
                                cellView.setInsuredEntity(currInsuredEntity);
                            }
                        }
                    }
                    callChanged(9);
                } else {
                    callChanged(0);
                }
                updateRelation();
            }
        }
    };

    private void setCareerByCode(int careerCode) {
        String careerName = Dictionary.DictionaryUtils.getCareerNameByCode(careerCode);
        if (!TextUtils.isEmpty(careerName)) {
            currentCareerCode = careerCode;
            propertyCareer.setValue(careerName);
        }
    }

    public void setRelationByCode(int relationCode) {
        String relationName = Dictionary.DictionaryUtils.getRelationNameByCode(relationCode);
        if (!TextUtils.isEmpty(relationName)) {
            currentRelationCode = relationCode;
            propertyRelationWith.setValue(relationName);
            updateRelation();
        }
    }

    private void updateRelation() {
        if (currentRelationCode == -1 || currentRelationCode == 0) {
            // 如果是本人,隐藏详细信息
            proposalPerson.hide();
            proposalHeader.setImportEnabled(false);
        } else {
            proposalPerson.show();
            proposalHeader.setImportEnabled(true);
        }
    }

    public void callChanged(int type) {
        if (onInsuredChangedListener != null) {
            onInsuredChangedListener.onInsuredChanged(type);
        }
    }

    /****************************************************/

    /**
     * 导入客户必须的对象
     *
     * @param manager
     */
    public InsuredView supportFragmentManager(FragmentManager manager) {
        this.fragmentManager = manager;
        if (proposalPerson != null) {
            proposalPerson.setFragmentManager(manager);
        }
        return this;
    }

    /**
     * 获取当前的与被保人关系
     *
     * @return
     */
    public String getRelationName() {
        return propertyRelationWith.getValue();
    }

    /**
     * 取出数据
     *
     * @return
     */
    public Customer getCustomer() {
        Customer customer = proposalPerson.getCustomer();
        if (customer != null) {
            if (currentCareerCode == 0) {
                currentCareerCode = 1; // 职业类别改为1-6, 如果原来为0,则改为1
            }
            customer.setCareerCategory(currentCareerCode);
            customer.setRelationWith(currentRelationCode);
        }
        return customer;
    }

    /**
     * 取出数据
     *
     * @return
     */
    public InsuredEntity getInsured() {
        return DataUtils.toInsured(getCustomer());
    }

    /**
     * 绑定数据
     *
     * @param insured
     */
    public void bindData(InsuredEntity insured) {
        if (insured != null) {
            proposalPerson.setCustomer(DataUtils.toCustomer(insured));
            setCareerByCode(insured.profession);
            setRelationByCode(insured.relation);
        }
    }

    /**
     * 绑定数据
     *
     * @param customer
     */
    public void bindData(Customer customer) {
        if (customer != null) {
            proposalPerson.setCustomer(customer);
            if (customer.getCareerCategory() != null) {
                setCareerByCode(customer.getCareerCategory());
            }
            if (customer.getRelationWith() != null) {
                setRelationByCode(customer.getRelationWith());
            }
        }
    }

    public void setInsuredChangedListener(onInsuredChangedListener listener) {
        onInsuredChangedListener = listener;
    }

    private BusinessConfig businessConfig;

    public void setBusinessConfig(BusinessConfig config) {
        businessConfig = config;
        proposalPerson.setBusinessConfig(businessConfig);
        propertyRelationWith.setType(ProposalPropertyItem.TYPE_RELATION);
        propertyRelationWith.setBusinessConfig(businessConfig);
        propertyCareer.setType(ProposalPropertyItem.TYPE_PROFESSION);
        propertyCareer.setBusinessConfig(businessConfig);
    }

    public interface onInsuredChangedListener {
        /**
         * 被保人信息变更
         *
         * @param type = 9 改变的是与投保人关系，并且切换到了本人
         */
        void onInsuredChanged(int type);
    }

    public int getRelation() {
        if (propertyRelationWith == null) {
            return -1;
        }
        return propertyRelationWith.getRelation();
    }

    public void setCorrespondingInsuranceView(InsuranceView insuranceView) {
        correspondingInsuranceView = insuranceView;
    }

    public void setCorrespondingApplicantView(ApplicantView applicantView) {
        correspondingApplicantView = applicantView;
    }

    public InsuranceView getCorrespondingInsuranceView() {
        return correspondingInsuranceView;
    }

    public ApplicantView getCorrespondingApplicantView() {
        return correspondingApplicantView;
    }

    private CheckOtherRelationCallBack otherRelationCallBack;

    public void setCheckOtherRelationCallBack(CheckOtherRelationCallBack checkOtherRelationCallBack) {
        this.otherRelationCallBack = checkOtherRelationCallBack;
    }

    /**
     * 选择多被保人的关系时与其他被保人进行校验
     */
    public interface CheckOtherRelationCallBack {
        boolean checkOtherRelation(int relationCode);
    }
}
